from flask import request

from utils.exceptions import custom_abort
from . import api
from utils.decorators.check_sign import check_sign
from utils.session import session
from plugins_v3.physical import config
from plugins_v3._login.login import physical_login
from utils.decorators.request_limit import request_limit
from utils.decorators.cache import cache


@api.route('/physical', methods=['GET'])
@check_sign(check_args={'name', 'passwd'})
@request_limit(5)
@cache({'name'}, 300)
def physical():
    name = request.args.get('name', type=str)
    passwd = request.args.get('passwd', type=str)
    cookies = physical_login(name, passwd)
    session.get(url=config.pre_url, cookies=cookies)
    rs = session.post(url=config.sys_url, cookies=cookies)
    userid = rs.json()['data'][0]['sysUser']['id']
    post_data = {
        'userId': userid
    }
    rq = session.post(url=config.index_url, data=post_data, cookies=cookies).json()
    if rq['returnCode'] != '200':
        custom_abort(-1, rq['returnMsg'])
    return {
        'code': 0,
        'data': rq['data']
    }


@api.route('/physical/details', methods=['GET'])
@check_sign(check_args={'meaScoreId'})
@request_limit(10)
@cache({'meaScoreId'}, 300)
def physical_details():
    grade_id = request.args.get('meaScoreId', type=str)
    post_data = {
        'meaScoreId': grade_id
    }
    rq = session.post(config.details_url, data=post_data).json()
    if rq['returnCode'] != '200':
        custom_abort(-1, rq['returnMsg'])
    return {
        'code': 0,
        'data': rq['data']
    }



